Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

331
Views
How to validate floating number in [input type=text]

I need a regular expression which validate the floating point number, I have build the following.

<label for="salary">Enter floating nunmber:</label>
<input type="text" id="salary" name="salary" oninput="this.value = this.value.replace(/[^-0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(/(\-.*)\-/g, '$1');" />

It works but it fails in case of 11-111. How to I fix it.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Maybe something like this:

const validateFloat = (e) => {
    let val = e.currentTarget.value;
    if(isNaN(val)){
        val = val.replace(/[^-0-9\.]/g,'');
        if(val.split('.').length>2) 
             val =val.replace(/\.+$/,"");
    }
    e.currentTarget.value = val; 
}

Using:

input.addEventListener("input", validateFloat); 

Working with negative values too.

about 4 years ago · Juan Pablo Isaza Report

0

You can use this this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1') like:

<label for="salary">Enter floating nunmber:</label>
<input type="text" id="salary" name="salary" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')" />

about 4 years ago · Juan Pablo Isaza Report

0

The sort of input validation you are trying here is going to be monstrous in a single regEx so you would be better off breaking it into several smaller ones

  • /[^0-9-.]/g to remove any none valid characters
  • /(-.*)-/g to remove any extra -
  • /(\..*)\./g to remove any extra .

this would look like this

let val = '-abc123.45.67-89';

val = val.replace(/[^0-9-.]/g, '');
val = val.replace(/(-.*?)-/g, '$1');
val = val.replace(/(\..*?)\./g, '$1');

console.log(val)
//"-123.456789"

if you are performing this on every char input then this should work fine however on bulk entry (ie a paste) you may need to loop the replaces to take into account that previous matches wont be included in the next match

eg

let val = '-123-abc.123.45.67-89';

val = val.replace(/[^0-9-.]/g, '');
const minusMatch = /(-.*?)-/g;
while(val.search(minusMatch)>=0){
    val = val.replace(minusMatch, '$1');
}
const dotMatch = /(\..*?)\./g;
while(val.search(dotMatch)>=0){
    val = val.replace(dotMatch, '$1');
}
console.log(val)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!